// 定义 Pinia store
import { defineStore } from 'pinia'
import { sendVerificationCode, sendVerificationCodeByMail } from '@/api/login'
import { MessagePlugin } from 'tdesign-vue-next'

export const useGlobalStore = defineStore('global', {
  state: () => ({
    countdown: 0
  }),
  actions: {
    async getCaptcha(mobile) {
      const { countdown } = this.$state
      if (countdown > 0) {
        MessagePlugin.error(`请${countdown}秒后再发送验证码`)
        return
      }
      if (mobile) {
        const data = {
          phoneNumber: mobile
        }
        await sendVerificationCode(data).then(res => {
          if (res.code === 200) {
            MessagePlugin.success('验证码发送成功')
          } else {
            MessagePlugin.error(res.error)
          }
        })
      }
      this.$state.countdown = 60
      const timer = setInterval(() => {
        if (this.$state.countdown <= 0) {
          clearInterval(timer)
        } else {
          this.$state.countdown--
        }
      }, 1000)
    },
    async getCaptchaByMail(mail) {
      const { countdown } = this.$state
      if (countdown > 0) {
        MessagePlugin.error(`请${countdown}秒后再发送验证码`)
        return
      }
      if (mail) {
        const data = {
          email: mail
        }
        //console.log(mail)
        //console.log(typeof mail)
        await sendVerificationCodeByMail(data).then(res => {
          //console.log(res)
          if (res.code === 200) {
            MessagePlugin.success('验证码发送成功')
          } else {
            MessagePlugin.error(res.error)
          }
        })
      }
      this.$state.countdown = 60
      const timer = setInterval(() => {
        if (this.$state.countdown <= 0) {
          clearInterval(timer)
        } else {
          this.$state.countdown--
        }
      }, 1000)
    }
  }
})
